﻿using System;

namespace Operations
{
    public sealed class OperationProcessor
    {
        private IOperation Operation { get; set; }

        public OperationProcessor SetAction(Func<IOperation> operation)
        {
            Operation = operation();
            ((CommonOpertation) Operation).Processor = this;
            return this;
        }

        public TResult Execute<TResult>()
        {
            return ExecuteOperation<TResult>().Result;
        }

        public void Execute()
        {
            ExecuteOperation<object>();
        }

        public bool CanExecute(out string error)
        {
            return Operation.CanExecute(out error);
        }

        #region Private methods

        private OperationResultWrapper<TResult> ExecuteOperation<TResult>()
        {
            var actionResult = new OperationResultWrapper<TResult>();
            Action<TResult> callback = x =>
            {
                actionResult.Result = x;
            };

            Operation.Execute(callback);
            return actionResult;
        }

        #endregion
    }
}